import { ref, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'

export const useApiMethod = ({ paramsMap, apiOption }) => {
  // 设置默认值
  paramsMap = {
    select: 'key',
    input: 'query',
    page: 'page',
    pageSize: 'pageSize',
    ...paramsMap
  }
  const searchParams = ref({
    [paramsMap.select]: '',
    [paramsMap.input]: '',
    [paramsMap.page]: 1,
    [paramsMap.pageSize]: 5
  })
  const total = ref(0)
  const tableDate = ref([])
  onMounted(() => {
    search()
  })
  const tableLoading = ref(false)

  const apiCallback = async ({ method, row, params }) => {
    if (!apiOption[method] || !apiOption[method].type) {
      return Promise.reject(new Error('未匹配到api'))
    }
    const item = apiOption[method]
    if (item.type === 'callback') {
      return Promise.resolve(item.callback(row))
    } else if (item.type === 'api') {
      tableLoading.value = true
      return item.api(params || { [apiOption.primaryKey]: row[apiOption.primaryKey] }).finally(() => {
        if (method !== 'list') {
          search()
        }
        tableLoading.value = false
      })
    } else {
      return Promise.reject(new Error('未匹配到api'))
    }
  }
  // 搜索
  const search = async () => {
    const { dataInfo } = await apiCallback({ method: 'list', params: searchParams.value })
    total.value = dataInfo.count
    tableDate.value = dataInfo.rows
  }
  // 创建
  const create = async () => {
    await apiCallback({ method: 'create' })
  }
  // 详情
  const read = async (row) => {
    await apiCallback({ method: 'read', row })
  }
  // 修改
  const update = async (row) => {
    await apiCallback({ method: 'update', row })
  }
  // 删除
  const del = (row) => {
    ElMessageBox.confirm('是否删除该行数据', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await apiCallback({ method: 'del', row })
      searchParams[paramsMap.page] = 1
    })
  }
  // 翻页
  const sizeChange = (e) => {
    searchParams.value[paramsMap.pageSize] = e
    search()
  }
  // 改变每页大小
  const currentChange = (e) => {
    searchParams.value[paramsMap.page] = e
    search()
  }

  return {
    searchParams,
    tableDate,
    total,
    tableLoading,
    search,
    create,
    read,
    update,
    del,
    sizeChange,
    currentChange
  }
}
